package com.yunc.common.utils;

import com.baidu.aip.util.Base64Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 百度人脸识别接口
 *
 * @author taocongcong
 * @create 2019-03-22 19:27
 */
public class QFaceUtil {

    public static String getToken() {
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();

        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String clientId = "LIWEBeO9iGZy5k6yyFFv1Ds9";
        String clientSecret = "ZrvN8LwdjuRG1uTmbD9EYUacf6pYnBrl";
        String getAccessTokenUrl = authHost
                + "grant_type=client_credentials"
                + "&client_id=" + clientId
                + "&client_secret=" + clientSecret;
        try {
            URL url = new URL(getAccessTokenUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.connect();
            br = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.fromObject(sb.toString());
        String token = jsonObject.getString("access_token");
        return token;
    }

    public boolean getResult(String imStr1, String imgStr2) {
        String accessToken = QFaceUtil.getToken();
        boolean flag = false;
        BufferedReader br = null;
        String result = "";
        String mathUrl = "https://aip.baidubce.com/rest/2.0/face/v3/match";
        String imStr2 = image2Base64(imgStr2);
        try {
            String params = URLEncoder.encode("images", "UTF-8") + "="
                    + URLEncoder.encode(imStr1 + imStr2, "UTF-8");
            String genrearlURL = mathUrl + "?access_token=" + accessToken;
            URL url = new URL(genrearlURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setDoInput(true);
            connection.setDoOutput(true);

            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            while ((line = br.readLine()) != null) {
                result += line;
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);

        // result ="{"error_msg":"Unsupported openapi method","error_code":3}"
        JSONObject fromObject = JSONObject.fromObject(result);
        JSONArray jsonArray = fromObject.getJSONArray("result");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = (JSONObject) jsonArray.get(i);
            double resultList = object.getDouble("score");
            if (resultList >= 90) {
                flag = true;

            }
        }
        return flag;
    }

    public static String image2Base64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return Base64Util.encode(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }

    public static void main(String[] args) {
        String tonken = getToken();
        System.out.println(tonken);
    }
}
